import type { AxiosResponse } from 'axios';
import { BACKEND_ERROR_CODE, createFlatRequest, createRequest } from '@sa/axios';
import { useAuthStore } from '@/store/modules/auth';
import { $t } from '@/locales';
import { localStg } from '@/utils/storage';
import { getServiceBaseURL } from '@/utils/service';
import { useRouterPush } from '@/hooks/common/router';
import { handleRefreshToken, showErrorMsg } from './shared';
import type { RequestInstanceState } from './type';

const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL, otherBaseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);

export const request = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    baseURL: `${baseURL}`
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = localStg.get('token');
      const Authorization = token ? `${token}` : null;
      Object.assign(headers, { Authorization });

      return config;
    },
    isBackendSuccess(response) {
      // when the backend response code is "0000"(default), it means the request is success
      // to change this logic by yourself, you can modify the `VITE_SERVICE_SUCCESS_CODE` in `.env` file
      return (
        Number.parseInt(String(response.data.code), 10) ===
        Number.parseInt(import.meta.env.VITE_SERVICE_SUCCESS_CODE, 10)
      );
    },
    async onBackendFail(response) {
      if (response.data.code !== 0) {
        window.$message?.error(response.data.message);
        return null;
      }
      // when the backend response code is in `logoutCodes`, it means the user will be logged out and redirected to login page
      // const logoutCodes = import.meta.env.VITE_SERVICE_LOGOUT_CODES?.split(',') || [];
      // if (logoutCodes.includes(response.data.code)) {
      //   handleLogout();
      //   return null;
      // }

      // // when the backend response code is in `modalLogoutCodes`, it means the user will be logged out by displaying a modal
      // const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      // if (
      //   modalLogoutCodes.includes(response.data.code) &&
      //   !request.state.errMsgStack?.includes(response.data.message)
      // ) {
      //   request.state.errMsgStack = [...(request.state.errMsgStack || []), response.data.message];

      //   // prevent the user from refreshing the page
      //   window.addEventListener('beforeunload', handleLogout);

      //   window.$dialog?.error({
      //     title: 'Error',
      //     content: String(response.data.code),
      //     positiveText: $t('common.confirm'),
      //     maskClosable: false,
      //     onPositiveClick() {
      //       logoutAndCleanup();
      //     },
      //     onClose() {
      //       logoutAndCleanup();
      //     }
      //   });

      //   return null;
      // }

      // // when the backend response code is in `expiredTokenCodes`, it means the token is expired, and refresh token
      // // the api `refreshToken` can not return error code in `expiredTokenCodes`, otherwise it will be a dead loop, should return `logoutCodes` or `modalLogoutCodes`
      // const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      // if (expiredTokenCodes.includes(response.data.code) && !request.state.isRefreshingToken) {
      //   request.state.isRefreshingToken = true;

      //   const refreshConfig = await handleRefreshToken(response.config);

      //   request.state.isRefreshingToken = false;

      //   if (refreshConfig) {
      //     return instance.request(refreshConfig) as Promise<AxiosResponse>;
      //   }
      // }

      return null;
    },

    transformBackendResponse(response) {
      return response.data.data;
    },
    onError(error) {
      // console.log(error.response);
      // when the request is fail, you can show error message
      const authStore = useAuthStore();

      function handleLogout() {
        authStore.resetStore();
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        request.state.errMsgStack = request.state.errMsgStack.filter(msg => msg !== error.response?.data.message);
      }

      const message = error.message;

      const ErrorCode = error.response?.status ? error.response?.status : 200;
      // get backend error message and code
      // if (ErrorCode === 401) {
      //   window.$dialog?.error({
      //     title: 'Error',
      //     content: $t('request.logoutMsg'),
      //     positiveText: $t('common.confirm'),
      //     maskClosable: false,
      //     onPositiveClick() {
      //       logoutAndCleanup();
      //     },
      //     onClose() {}
      //   });
      //   return;
      // }
      if (ErrorCode >= 200 && ErrorCode < 300) return;

      switch (ErrorCode) {
        case 401:
          logoutAndCleanup();
          return;

        case 403:
          showErrorMsg(request.state, $t('route.403'));
          return;

        case 404:
          showErrorMsg(request.state, $t('route.404'));
          break;
        default:
          showErrorMsg(request.state, message);
          break;
      }

      // // the error message is displayed in the modal
      // const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      // if (modalLogoutCodes.includes(backendErrorCode)) {
      //   return;
      // }

      // // when the token is expired, refresh token and retry request, so no need to show error message
      // const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      // if (expiredTokenCodes.includes(backendErrorCode)) {
      //   return;
      // }

      // showErrorMsg(request.state, message);
    }
  }
);

/** V1 版本的API */
export const requestV1 = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    baseURL: `${baseURL}/v1`
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = localStg.get('token');
      const Authorization = token ? `${token}` : null;
      Object.assign(headers, { Authorization });

      return config;
    },
    isBackendSuccess(response) {
      // when the backend response code is "0000"(default), it means the request is success
      // to change this logic by yourself, you can modify the `VITE_SERVICE_SUCCESS_CODE` in `.env` file
      return response.data.code === 0;
    },
    async onBackendFail(response) {
      if (response.data.code === 581) {
        // 未启用数据转发
        // window.$message?.error('aaaa');
        window.$dialog?.error({
          title: $t('common.error'),
          content: $t('page.kernel.notForward'),
          positiveText: $t('common.confirm'),
          negativeText: $t('common.cancel'),
          maskClosable: false,
          onPositiveClick() {
            useRouterPush(false).routerPushByKey('system_kernel');
          },
          onClose() {}
        });
        return null;
      }

      if (response.data.code > 10) {
        window.$message?.error(response.data.message);
        return null;
      }
      return null;
    },

    transformBackendResponse(response) {
      return response.data.data;
    },
    onError(error) {
      // console.log(error);
      if (error.code === 'ECONNABORTED') {
        window.$message?.error(`请求超时: ${error.message}`);
        return;
      }
      // when the request is fail, you can show error message
      const authStore = useAuthStore();

      function handleLogout() {
        authStore.resetStore();
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        error.request.state.errMsgStack = error.request.state.errMsgStack.filter(
          (msg: any) => msg !== error.response?.data.message
        );
      }

      const ErrorCode = error.response?.status ? error.response.status : 200;

      if (ErrorCode >= 200 && ErrorCode < 300) return;

      switch (ErrorCode) {
        case 401:
          logoutAndCleanup();
          return;

        case 403:
          window.$message?.error($t('route.403'));
          return;

        case 404:
          window.$message?.error($t('route.404'));
          return;

        case 406:
          window.$message?.error($t('route.406'));
          useRouterPush(false).routerPushByKey('406');
          break;

        case 500:
          window.$message?.error($t('route.500'));
          return;

        default:
          window.$message?.error(error.message);
          break;
      }
    }
  }
);

export const requestBAK = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    baseURL,
    headers: {
      apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2'
    }
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = localStg.get('token');
      const Authorization = token ? `Bearer ${token}` : null;
      Object.assign(headers, { Authorization });

      return config;
    },
    isBackendSuccess(response) {
      // when the backend response code is "0000"(default), it means the request is success
      // to change this logic by yourself, you can modify the `VITE_SERVICE_SUCCESS_CODE` in `.env` file
      return String(response.data.code) === import.meta.env.VITE_SERVICE_SUCCESS_CODE;
    },
    async onBackendFail(response, instance) {
      const authStore = useAuthStore();

      function handleLogout() {
        authStore.resetStore();
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        request.state.errMsgStack = request.state.errMsgStack.filter(msg => msg !== response.data.message);
      }

      // when the backend response code is in `logoutCodes`, it means the user will be logged out and redirected to login page
      const logoutCodes = import.meta.env.VITE_SERVICE_LOGOUT_CODES?.split(',') || [];
      if (logoutCodes.includes(String(response.data.code))) {
        handleLogout();
        return null;
      }

      // when the backend response code is in `modalLogoutCodes`, it means the user will be logged out by displaying a modal
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (
        modalLogoutCodes.includes(String(response.data.code)) &&
        !request.state.errMsgStack?.includes(response.data.message)
      ) {
        request.state.errMsgStack = [...(request.state.errMsgStack || []), response.data.message];

        // prevent the user from refreshing the page
        window.addEventListener('beforeunload', handleLogout);

        window.$dialog?.error({
          title: $t('common.error'),
          content: response.data.message,
          positiveText: $t('common.confirm'),
          maskClosable: false,
          closeOnEsc: false,
          onPositiveClick() {
            logoutAndCleanup();
          },
          onClose() {
            logoutAndCleanup();
          }
        });

        return null;
      }

      // when the backend response code is in `expiredTokenCodes`, it means the token is expired, and refresh token
      // the api `refreshToken` can not return error code in `expiredTokenCodes`, otherwise it will be a dead loop, should return `logoutCodes` or `modalLogoutCodes`
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(String(response.data.code)) && !request.state.isRefreshingToken) {
        request.state.isRefreshingToken = true;

        const refreshConfig = await handleRefreshToken(response.config);

        request.state.isRefreshingToken = false;

        if (refreshConfig) {
          return instance.request(refreshConfig) as Promise<AxiosResponse>;
        }
      }

      return null;
    },
    transformBackendResponse(response) {
      return response.data.data;
    },
    onError(error) {
      // when the request is fail, you can show error message

      let message = error.message;
      let backendErrorCode = '';

      // get backend error message and code
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.message || message;
        backendErrorCode = error.response?.data?.code ? String(error.response?.data?.code) : '';
      }

      // the error message is displayed in the modal
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (modalLogoutCodes.includes(backendErrorCode)) {
        return;
      }

      // when the token is expired, refresh token and retry request, so no need to show error message
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(backendErrorCode)) {
        return;
      }

      showErrorMsg(request.state, message);
    }
  }
);

export const demoRequest = createRequest<App.Service.DemoResponse>(
  {
    baseURL: otherBaseURL.demo
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = localStg.get('token');
      const Authorization = token ? `Bearer ${token}` : null;
      Object.assign(headers, { Authorization });

      return config;
    },
    isBackendSuccess(response) {
      // when the backend response code is "200", it means the request is success
      // you can change this logic by yourself
      return response.data.status === '200';
    },
    async onBackendFail(_response) {
      // when the backend response code is not "200", it means the request is fail
      // for example: the token is expired, refresh token and retry request
    },
    transformBackendResponse(response) {
      return response.data.result;
    },
    onError(error) {
      // when the request is fail, you can show error message

      let message = error.message;

      // show backend error message
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.message || message;
      }

      window.$message?.error(message);
    }
  }
);

export const requestBase = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    baseURL: `${baseURL}`
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = localStg.get('token');
      const Authorization = token ? `${token}` : null;
      Object.assign(headers, { Authorization });

      return config;
    },
    isBackendSuccess() {
      return true;
    },
    async onBackendFail(response) {
      if (response.data.code !== 0) {
        window.$message?.error(response.data.message);
        return null;
      }

      return null;
    },

    transformBackendResponse(response) {
      return response.data;
    },
    onError(error) {
      // console.log(error.response);
      // when the request is fail, you can show error message
      const authStore = useAuthStore();

      function handleLogout() {
        authStore.resetStore();
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        request.state.errMsgStack = request.state.errMsgStack.filter(msg => msg !== error.response?.data.message);
      }

      const message = error.message;

      const ErrorCode = error.response?.status ? error.response?.status : 200;

      if (ErrorCode >= 200 && ErrorCode < 300) return;

      switch (ErrorCode) {
        case 401:
          logoutAndCleanup();
          return;

        case 403:
          showErrorMsg(request.state, $t('route.403'));
          return;

        case 404:
          showErrorMsg(request.state, $t('route.404'));
          return;

        default:
          showErrorMsg(request.state, message);
          break;
      }
    }
  }
);
